#include<stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <sys/stat.h>
#define FALSE 0
#define TRUE 1

static const char *tc_main_pid_file = "/tmp/ap_tcmd.pid";	/* Storage location of current PID */

int tc_main_lock_process(void)
{
	int success = FALSE;
	FILE *fp = NULL;
	int fd = -1;
	int pid = 0;

	/* Write PID to file, set PID file to read/write for owner, read by others */
	if ((fd = open(tc_main_pid_file, (O_RDWR | O_CREAT), 0644)) != -1) {
		if ((fp = fdopen(fd, "r+")) != NULL) {
			if (flock(fd, (LOCK_EX | LOCK_NB)) < 0) {
				fscanf(fp, "%d", &pid);
				printf("Can't lock process, lock held by pid %d", pid);
			}
			else {
				printf("else\n");
				pid = getpid();
				if ((fprintf(fp, "%d", pid)) && (!fflush(fp)) && (!flock(fd, LOCK_UN))) {
					success = TRUE;
				}
			}
			fclose(fp);
		}
		close(fd);
	}
	return (success);
}
int main(int argc, char *argv[])
{
    tc_main_lock_process();
    
    return 0;
}
